<?php


namespace app\admin\model;


use app\common\traits\ActionRecordTrait;
use think\facade\Db;

class Article extends Common
{

    use ActionRecordTrait;

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如CRM模块用crm作为数据表前缀
     */
    protected $name = 'admin_article';

    /**
     * 列表
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 11:48
     */
    public function getDataList(array $request): array
    {
        try {
            $request['page']  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
            $request['limit'] = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
            $title      = isset($request['title']) && trim($request['title']) ? trim($request['title']) : '';
            $categoryId = isset($request['category_id']) && intval($request['category_id']) ? intval($request['category_id']) : 0;
            $where      = [];
            $title && array_push($where, ['title', 'like', '%'.$title.'%']);
            $categoryId && array_push($where, ['category_id', '=', $categoryId]);
            $dataCount = $this->where($where)->count();
            if ($dataCount) {
                $field = ['article_id', 'author', 'title', 'category_id', 'desc', 'create_user_id', 'create_time', 'update_time'];
                $list  = $this->where($where)->field($field)->order('article_id DESC')
                    ->limit(($request['page'] - 1) * $request['limit'], $request['limit'])
                    ->select()->toArray();
                $userIdArr = array_unique(array_column($list, 'create_user_id'));
                $userList  = Db::name('admin_user')->where('id', 'in', $userIdArr)->column('realname', 'id');
                $categoryIdArr = array_unique(array_column($list, 'category_id'));
                $categoryList  = Db::name('admin_article_category')->where('id', 'in', $categoryIdArr)->column('name', 'id');
                foreach ($list as $key => $val) {
                    $list[$key]['category_name']    = $categoryList[$val['category_id']] ?? '';
                    $list[$key]['create_user_name'] = $userList[$val['create_user_id']] ?? '';
                    unset($list[$key]['create_user_id']);
                }
            }

            $data              = [];
            $data['list']      = $list ?? [];
            $data['dataCount'] = $dataCount ?? 0;
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '暂无此数据';
        return [];
    }

    /**
     * 添加
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 13:45
     */
    public function addData(array $request): bool
    {
        try {
            $validate = new \app\admin\validate\Article();
            if (!$validate->scene('create')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }

            $data = [
                'category_id'    => intval($request['category_id']),
                'author'         => isset($request['author']) ? trim($request['author']) : '',
                'title'          => trim($request['title']),
                'desc'           => isset($request['desc']) ? trim($request['desc']) : '',
                'cover'          => isset($request['cover']) ? trim($request['cover']) : '',
                'create_user_id' => $request['user_id'],
                'content'        => $request['content'],
                'create_time'    => time(),
                'update_time'    => time()
            ];
            $articleId = $this->insertGetId($data);
            if ($articleId) {
                // 添加操作记录
                $logCode = json_encode($data, JSON_UNESCAPED_UNICODE);
                $this->addActionRecord($request['user_id'], 'admin_article_create', $articleId, '创建了文章', 'admin', 'article', $logCode);

                $this->error = '添加成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '添加失败';
        return false;
    }

    /**
     * 编辑
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 13:55
     */
    public function saveData(array $request): bool
    {
        try {
            $userId   = $request['user_id'] ?? 0;
            $validate = new \app\admin\validate\Article();
            if (!$validate->scene('update')->check($request)) {
                $this->error = $validate->getError();
                return false;
            }

            $articleId = $request['article_id'];
            $field     = ['author', 'title', 'desc', 'category_id', 'cover', 'content'];
            $info      = $this->where(['article_id' => $articleId])->field($field)->find();
            if (!$info) {
                $this->error = '文章信息不存在';
                return false;
            }

            // 判断是否是管理员
            if ($info['category_id'] == 1 && !in_array($userId, getSuperAdminId())) {
                $this->error = '默认分类、暂无权限编辑';
                return false;
            }

            $data = [
                'category_id' => intval($request['category_id']),
                'author'      => isset($request['author']) ? trim($request['author']) : '',
                'title'       => trim($request['title']),
                'desc'        => isset($request['desc']) ? trim($request['desc']) : '',
                'cover'       => isset($request['cover']) ? trim($request['cover']) : '',
                'content'     => $request['content'],
                'update_time' => time()
            ];
            $bool = $this->where(['article_id' => $articleId])->update($data);
            if ($bool) {
                // 添加操作记录
                $logFieldArr = [
                    'category_id' => '分类',
                    'author'      => '作者',
                    'title'       => '文章标题',
                    'desc'        => '简介',
                    'cover'       => '封面',
                    'content'     => '内容'
                ];
                if ($info['category_id'] != $data['category_id']) {
                    $categoryIdArr = [$info['category_id'], $data['category_id']];
                    $categoryList  = Db::name('admin_article_category')->where('id', 'in', $categoryIdArr)->column('name', 'id');
                }
                $logContentArr = [];
                foreach ($logFieldArr as $key => $val) {
                    if ($data[$key] != $info[$key]) {
                        if ($key == 'category_id' && isset($categoryList)) {
                            $info[$key] = $categoryList[$info[$key]];
                            $data[$key] = $categoryList[$data[$key]];
                        }
                        if ($key == 'content') {
                            $logContentArr[] = "修改了文章内容";
                        } else {
                            $logContentArr[] = "将 '" . $val . "' 由 " . $info[$key] . " 修改为 " . $data[$key];
                        }
                    }
                }
                if ($logContentArr) {
                    $logData       = $data;
                    $logContentStr = implode('.|.', $logContentArr);
                    $logCode       = json_encode($logData, JSON_UNESCAPED_UNICODE);
                    $this->addActionRecord($request['user_id'], 'admin_article_update', $articleId, $logContentStr, 'admin', 'article', $logCode);
                }

                $this->error = '编辑成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '编辑失败';
        return false;
    }

    /**
     * 详情
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 14:08
     */
    public function getDataInfo(array $request): array
    {
        try {
            $articleId = $request['article_id'] ?? 0;
            if (!$articleId) {
                $this->error = '参数错误';
                return [];
            }

            $field = [];
            $info  = $this->where(['article_id' => $articleId])->field($field)->find();
            if (!$info) {
                $this->error = '文章信息不存在';
                return [];
            }

            $info['cover_path'] = $info['cover'] ? config('app.img_url').$info['cover'] : '';
            $info['create_user_name'] = Db::name('admin_user')->where(['id' => $info['create_user_id']])->value('realname');
            $info['category_name']    = Db::name('admin_article_category')->where(['id' => $info['category_id']])->value('name');
            unset($info['create_user_id']);

            $this->error = '获取成功';
            return $info->toArray();
        } catch (\Exception $e) {
        }

        $this->error = '编辑失败';
        return [];
    }

    /**
     * 删除
     * @param  array $request 请求参数
     * @return bool
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 14:27
     */
    public function deleteData(array $request): bool
    {
        try {
            $articleId = $request['article_id'] ?? [];
            if (!$articleId || !is_array($articleId)) {
                $this->error = '参数错误';
                return false;
            }

            $list = $this->where('article_id', 'in', $articleId)->select()->toArray();
            if (!$list) {
                $this->error = '请选择文章';
                return false;
            }

            $articleIdArr  = array_column($list, 'article_id');
            $categoryIdArr = array_unique(array_column($list, 'category_id'));
            // 判断是否是管理员
            if (in_array(1, $categoryIdArr)) {
                $this->error = '选择默认分类下的文章不可删除';
                return false;
            }

            $bool = $this->where('article_id', 'in', $articleIdArr)->delete();
            if ($bool) {
                // 添加操作记录
                foreach ($list as $key => $val) {
                    if (in_array($val['article_id'], $articleIdArr)) {
                        $logCode = json_encode($val, JSON_UNESCAPED_UNICODE);
                        $this->addActionRecord($request['user_id'], 'admin_article_delete', $val['article_id'], '删除了文章', 'admin', 'article', $logCode);
                    }
                }

                $this->error = '删除成功';
                return true;
            }
        } catch (\Exception $e) {
        }

        $this->error = '删除失败';
        return false;
    }

    /**
     * 全部分类
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-23 17:01
     */
    public function getCategoryDataList(array $request): array
    {
        try {
            $where = [];
            $field = ['id', 'name'];
            $list  = (new ArticleCategory())->getArticleCategoryList($where, $field);
            $data['data'] = $list ?: [];
            return $data;
        } catch (\Exception $e) {
        }

        $this->error = '暂无分类数据';
        return [];
    }

    /**
     * 操作记录
     * @param  array $request 请求参数
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-24 8:41
     */
    public function getRecordList(array $request): array
    {
        $id = $request['id'] ?? 0;
        if (!$id) {
            $this->error = '参数错误';
            return [];
        }

        $page  = isset($request['page']) && intval($request['page']) ? intval($request['page']) : 1;
        $limit = isset($request['limit']) && intval($request['limit']) ? intval($request['limit']) : 15;
        return $this->getActionRecordListByPage($id, 'admin', 'article', 0, $page, $limit);
	}

	/**
     * 根据条件获取信息
     * @param  array $where 查询条件
     * @param  array $field 查询字段
     * @return array
     * @author Mr.Liu Wuchen
     * @create 2021-06-25 10:51
     */
    public function getArticleList(array $where = [], array $field = []): array
    {
        try {
            $list = $this->where($where)->field($field)->select()->toArray();
        } catch (\Exception $e) {
        }

        return isset($list) && $list ? $list : [];
    }

}
